﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Threading.Thread;
using static System.Console;
using System.Threading;

namespace Project_2
{
    /// <summary>
    /// 2.4 使用 SemaphoreSlim 类,限制同时访问同一个资源的线程数量
    /// </summary>
    public class Unit_2_04
    {
        /*
         * SemaphoreSlim _semaphore = new SemaphoreSlim(4);
         * 限制同时访问同一资源的线程数量
         * _semaphore.Wait();//阻止当前线程，直到可进入为止
         * (前面的线程释放一个SemaphoreSlim，同时访问资源的线程数小于设置的值)
         * _semaphore.Release();//释放一个SemaphoreSlim
         */
        public static void Go()
        {
            for (int i = 1; i <= 20; i++)
            {
                string threadName = "Thread" + i;
                int secondsToWait = 4;
                var t=new Thread(()=>AccessDatabase(threadName,secondsToWait));
                t.Start();
            }
        }

        static SemaphoreSlim _semaphore = new SemaphoreSlim(4);

        static void AccessDatabase(string name, int seconds)
        {
            WriteLine($"{name} 等待访问数据库");
            _semaphore.Wait();
            WriteLine($"{name} 被授予访问数据库的权限 ");
            Sleep(TimeSpan.FromSeconds(seconds));
            WriteLine($"{name} 完成了");
            _semaphore.Release();
        }
    }
}
